import { Component, ElementRef, OnInit, Input, ViewChild, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-scroll-up',
  templateUrl: './scroll-up.component.html',
  styleUrls: ['./scroll-up.component.less'],
  encapsulation: ViewEncapsulation.Emulated,
})
export class ScrollUpComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  @Input()
  public dataObj: any = {
    time: 50,
    minLength: 1,
    width:200,
    height: 200,
    unit: 'px',
    scrollList: ['1111','2222','3333','444','555','666']
  }
  
  @ViewChild('outerMost', { static: false }) outerMost: ElementRef;
  @ViewChild('outerBox1', { static: false }) outerBox1: ElementRef;
  @ViewChild('outerBox2', { static: false }) outerBox2: ElementRef;

  ngAfterViewInit() {
    setTimeout(()=>{this.roll(this.dataObj.time)},1000)
  }
  timer = null
  ngOnDestroy() {
    if (this.timer) clearInterval(this.timer);
  }
  roll(t) {
    var outerMost = this.outerMost.nativeElement
    if (this.dataObj.scrollList.length < this.dataObj.minLength) { return console.log('不需要滚动') }
    outerMost.scrollTop = 0;
    this.rollStart(t);
  }
  rollStart(t) {
    var outerMost = this.outerMost.nativeElement
    var outerBox1 = this.outerBox1.nativeElement
    this.rollStop('开始');
    this.timer = setInterval(() => {
      // 当滚动高度大于列表内容高度时恢复为0  
      outerMost.scrollTop++;
      if (outerBox1.scrollHeight - outerMost.scrollTop === 1) {
        outerMost.scrollTop = 0;
        outerMost.scrollTop++;
      }
      if (outerMost.scrollTop >= outerBox1.scrollHeight) {
        outerMost.scrollTop = 0;
        outerMost.scrollTop++;
      }
    }, t);
  }
  rollStop(e) {
    console.log(e)
    clearInterval(this.timer);
  }

}